# -*- coding: utf-8 -*-
#
# suspend.py
#
# Copyright (C) 2010 - Jakub Krajniak
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# The Rhythmbox authors hereby grant permission for non-GPL compatible
# GStreamer plugins to be used and distributed together with GStreamer
# and Rhythmbox. This permission is above and beyond the permissions granted
# by the GPL license by which Rhythmbox is covered. If you modify this code
# you may extend this exception to your version of the code, but you are not
# obligated to do so. If you do not wish to do so, delete this exception
# statement from your version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA.




import gobject, gconf
import gtk
import rhythmdb, rb
import dbus

import threading
import time

import config

ui_str = """
<ui>
  <toolbar name="ToolBar">
	<toolitem name="PowerOff" action="PowerOffAction" />
  </toolbar>
</ui>
"""

GConfPath = '/apps/rhythmbox/plugins/suspend/'

class SuspendPlugin(rb.Plugin):
	def __init__(self):
		rb.Plugin.__init__(self)
		self.window = None
		self.poweroff = False
		self.config_dialog = None
		self.dialog = None
		
		self.gconf = gconf.client_get_default()
		self.gconf.add_dir(config.GCONF_DIR, preload=False)
		self.gconf.notify_add(config.GCONF_KEYS['action'], self.action_changed_cb)
		self.gconf.notify_add(config.GCONF_KEYS['time'], self.time_changed_cb)
		
		self.poweroff_time = 60
		self.poweroff_action = 1 # 0 - poweroff, 1 - suspend
		self.poweroff_action_dict = { 0: 'Shutdown', 1: 'Suspend' }
		self.poweroff_action_func = {0: self.action_shutdown, 1: self.action_suspend}
		
		self.is_playing = False
		
	def activate(self, shell):
		self.ui = shell.get_ui_manager()

		action = gtk.ToggleAction('PowerOffAction', _('PowerOff'),
                		_("PowerOff computer after playlist end [OFF]"),
                		'gtk-quit')
		action_id = action.connect('activate', self.set_poweroff, shell)
		self.action_group = gtk.ActionGroup ('Poweroff')
		self.action_group.add_action (action)
		self.ui.insert_action_group(self.action_group, -1)
		self.ui_id = self.ui.add_ui_from_string(ui_str)
		self.ui.ensure_update()
		
		## bind to signal, end of playlist
		shell_player = shell.get_player()
		self.player_connect_id = shell_player.connect('playing-changed', self.playing_changed)
		
		self.load_config()
		
	def deactivate(self, shell):
		manager = shell.get_player().get_property('ui-manager')
		manager.remove_ui (self.ui_id)
		manager.remove_action_group(self.action_group)
		self.action_group = None
		shell.get_player().disconnect(self.player_connect_id)
		if self.dialog:
			self.dialog.destroy()
	
	def action_changed_cb(self, client, id, entry, d):
		gaction = self.gconf.get_int(config.GCONF_KEYS['action'])
		self.poweroff_action = gaction
	
	def time_changed_cb(self, client, id, entry, d):
		gtime = self.gconf.get_string(config.GCONF_KEYS['time'])
		self.poweroff_time = gtime
	
	def load_config(self):
		gtime = self.gconf.get_string(config.GCONF_KEYS['time'])
		gaction = self.gconf.get_int(config.GCONF_KEYS['action'])
		if gtime == None:
			gtime = 60
		else:
			gtime = int(gtime)
		
		if gaction not in [0,1]:
			gaction = 1
		
		self.poweroff_time = gtime
		self.poweroff_action = gaction
	
	def set_poweroff(self, shell, wtf):
		btn = self.ui.get_widget('/ToolBar/PowerOff')
		
		if self.poweroff:
			self.poweroff = False
			btn.set_tooltip_text(_("%s computer after playlist end [is OFF]" % (self.poweroff_action_dict[self.poweroff_action])))
		else:
			self.poweroff = True
			btn.set_tooltip_text(_("%s computer after playlist end [is ON]" % (self.poweroff_action_dict[self.poweroff_action])))
	
	def action_suspend(self):
		bus = dbus.SystemBus()
		proxy = bus.get_object('org.freedesktop.UPower', '/org/freedesktop/UPower')
		iface = dbus.Interface(proxy, 'org.freedesktop.UPower')
		ret = iface.Suspend()
		print 'POWER OFF', ret
		self.dialog.destroy()
	
	def action_shutdown(self):
		bus = dbus.SystemBus()
		proxy = bus.get_object('org.freedesktop.ConsoleKit', '/org/freedesktop/ConsoleKit/Manager')
		iface = dbus.Interface(proxy, 'org.freedesktop.ConsoleKit.Manager')
		iface.Stop()
		print 'SHUTDOWN'
		self.dialog.destroy()
	
	def playing_changed(self, player, playing):
		
		if not self.is_playing and playing:
			self.is_playing = True
		
		if not playing and self.poweroff and self.is_playing:
			self.dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_CANCEL, _("Computer will be %s after %d seconds. You can cancel this procedure now." % (self.poweroff_action_dict[self.poweroff_action], int(self.poweroff_time))))
			
			timer = threading.Timer(int(self.poweroff_time), self.poweroff_action_func[int(self.poweroff_action)])
			timer.start()
			
			response = self.dialog.run()
			if response == gtk.RESPONSE_CANCEL:
				timer.cancel()
				print 'cancel'
				self.is_playing = False
				
			self.dialog.destroy()
			
	def create_configure_dialog(self, dialog=None):
		if self.config_dialog is None:
			self.config_dialog = config.SuspendConfigDialog(self)
			self.config_dialog.connect('response', self.config_dialog_response_cb)
			
		self.config_dialog.present()
		return self.config_dialog
	
	def config_dialog_response_cb(self, dialog, response):
		print 'response cb'
		dialog.hide()
# ex:noet:ts=8:
